/** Copyright 2014, Ross Mahony. Some rights reserved. See COPYING. */
package models

import play.api.db.slick.Config.driver.simple._
import scala.slick.lifted.Tag

case class Measure(id: Option[Long], name: String, savingCost: Double,
  installCost: Double, savingCO2: Double)

/** Measure entity. */
class MeasureTbl(tag: Tag) extends Table[Measure](tag, "MSR") {

  def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME", O.NotNull)
  def savingCost = column[Double]("SV_COST", O.NotNull)
  def installCost = column[Double]("INST_COST", O.NotNull)
  def savingCO2 = column[Double]("SV_C02", O.NotNull)
  def * = (id.?, name, savingCost, installCost, savingCO2) <> (Measure.tupled, Measure.unapply _)
}

/** Measure DAO */
object MeasureDAO {
  val measures = TableQuery[MeasureTbl]
  
 /**
  * Retrieve a [[models.Measure]] by the id
  *
  * @param id
  */
  def findById(id: Long)(implicit s: Session): Option[Measure] =
  measures.where(_.id === id).firstOption

 /** Count all measures */
  def count(implicit s: Session): Int =
  Query(measures.length).first

 /**
  * Insert a new [[models.Measure]]
  *
  * @param measure
  */
  def insert(measure: Measure)(implicit s: Session) {
    measures.insert(measure)
  }

 /**
  * Insert a new measures by ignoring auto inc column
  *
  * @param measure
  */
  def forceInsert(measure: Measure)(implicit s: Session) {
    measures.forceInsert(measure)
  }

 /** Fetch all measures */
  def list(implicit s: Session) = {
     measures.sortBy(_.installCost).list
  }

 /** Delete all measures */
  def deleteAll(implicit s: Session) {
    measures.delete
  }

}
